import { Tabs, Modal, Form } from 'antd'
import { useEffect, useState, useRef, useMemo } from 'react'
import ProForm, {
  ProFormInstance,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form'
import { BraftEditor as BraftEditorPro } from '../BraftEditor'
import React from 'react'
import { request, useT } from '@designable/event-system'
import { registerDialogInstances } from '@designable/react'
import { v4 as uuidv4 } from 'uuid'
import { useParentForm } from '@formily/react'
import { FormLayout, FormItem } from '@formily/antd'
import { onFieldValueChange, onFieldInit } from '@formily/core'
import { Field } from '@formily/react'

function pageLabelLanguageList() {
  return request({
    uri: '/api/tenant/dic/saasLanguageList',
    method: 'GET',
  })
}

export function MultiLanguageDialog(props: {
  dialogName: string
  formType?: 'input' | 'textarea' | 'editor'
  nameKey: string
}) {
  const { dialogName, nameKey, formType = 'input' } = props
  const [languageList, setLanguageList] = useState<any[]>([])
  const [open, setOpen] = useState(false)
  const uuid = useMemo(() => uuidv4(), [])
  const formRef = useRef<ProFormInstance>()
  const t = useT()
  const form = useParentForm() as any
  const [initialValue, setInitialValue] = useState<any>({})

  const getPageLabelLanguageList = async () => {
    const res: any = await pageLabelLanguageList()
    setLanguageList(res)
  }

  const dialogProps = useMemo(
    () => ({
      open: (props) => {
        setOpen(true)
      },
      close: (props) => {
        setOpen(false)
      },
    }),
    []
  )

  useEffect(() => {
    const dispose = form.addEffects(nameKey, () => {
      onFieldValueChange(nameKey, (targetField) => {
        setInitialValue({
          [nameKey]: targetField.value.map((item: any) => ({ ...item })),
        })
      })
    })

    return () => dispose()
  }, [form])

  useEffect(() => {
    registerDialogInstances(uuid, {
      label: dialogName,
      value: dialogName,
      id: uuid,
      ...dialogProps,
    })
  }, [dialogName])

  useEffect(() => {
    open && getPageLabelLanguageList()
  }, [open])

  return (
    <>
      <div style={{ display: 'none' }}>
        <Field
          name={nameKey}
          component={[
            FormItem,
            {
              hidden: true,
              initialValue: [],
            },
          ]}
        />
      </div>
      <Modal
        title={' '}
        open={open}
        onOk={() => {
          const values = formRef.current?.getFieldsValue()
          form?.setValues?.({ ...values })
          setOpen(false)
        }}
        onCancel={() => {
          setOpen(false)
        }}
        width={900}
        destroyOnClose
        getContainer={() => {
          return (
            document.getElementById('designable-page-wrap') || document.body
          )
        }}
      >
        <FormLayout>
          <ProForm
            labelCol={{ span: 5, offset: 0 }}
            formRef={formRef}
            scrollToFirstError={true}
            layout="horizontal"
            name="validate_other"
            initialValues={initialValue}
            submitter={false}
          >
            {formType === 'editor' && (
              <Tabs
                type="card"
                items={languageList.map(({ name, code }, index) => {
                  return {
                    label: name,
                    key: code,
                    children: (
                      <>
                        <ProForm.Item name={[nameKey, index, 'message']}>
                          <BraftEditorPro />
                        </ProForm.Item>
                        <ProFormText
                          hidden
                          name={[nameKey, index, 'language']}
                          initialValue={code}
                        />
                      </>
                    ),
                  }
                })}
              />
            )}
            {formType !== 'editor' && (
              <Form.List name={nameKey}>
                {(fields, { add, remove }) => (
                  <>
                    {languageList.map(({ name, code }, index) => {
                      return (
                        <>
                          {formType === 'input' && (
                            <ProFormText
                              width="xl"
                              name={[index, 'message']}
                              label={name}
                            />
                          )}
                          {formType === 'textarea' && (
                            <ProFormTextArea
                              width="xl"
                              name={[index, 'message']}
                              label={name}
                            />
                          )}
                          <ProFormText
                            hidden
                            name={[index, 'language']}
                            initialValue={code}
                          />
                        </>
                      )
                    })}
                  </>
                )}
              </Form.List>
            )}
          </ProForm>
        </FormLayout>
      </Modal>
    </>
  )
}
